/**
 * 流量超市登录的业务逻辑
 */
import { appsAPI, appsAccountAPI } from '@/services/common/api'
import type { Account } from './definition'
import { account$, token$$ } from './info'

// 确认此服务在平台后台的的开通状态
const TOOL_ID = 'quntooldocker'
enum ToolStatus {
  Expired = 'expired', // 已过期
  Unpaid = 'unpaid', // 未购买
  Paid = 'paid', // 已购买
  Trial = 'trial', // 试用中
}
interface ToolStatusResp {
  expiry: string // 到期时间
  service: string // tool id
  state: -1 | 0 | 1 | 2 // 付费状态。见下方 map
}
export async function confirmUsable(_account: Account) {
  const result = await appsAPI<ToolStatusResp | null>(`/auth/auth?service=${TOOL_ID}`, {
    headers: { token: _account.token },
  })
  const map = {
    [-1]: ToolStatus.Expired,
    0: ToolStatus.Unpaid,
    1: ToolStatus.Paid,
    2: ToolStatus.Trial,
  }
  const status =
    result.success && result.data
      ? {
          expiry: new Date(result.data.expiry).getTime(),
          service: result.data.service,
          state: map[result.data.state],
        }
      : {
          expiry: -1,
          service: TOOL_ID,
          state: ToolStatus.Unpaid,
        }
  return status.state === ToolStatus.Paid || status.state === ToolStatus.Trial
}

export function gotToken(token: string) {
  token$$.next({ value: token, mayInvalid: false })
}

export async function logout(token?: string) {
  token$$.next(null)
  const res = await appsAccountAPI('loginout', {
    method: 'POST',
    data: { token: token ?? account$.value?.token ?? '' },
  })
  setTimeout(() => window.location.reload(), 500) // 刷新网页以保证断开原有的 mqtt 订阅等内容
  return res
}
